package com.cherry.sdk.http.token

import com.cherry.sdk.http.params.Params

import com.google.gson.Gson
import okhttp3.RequestBody
import retrofit2.Converter
import retrofit2.Retrofit
import java.lang.reflect.Type

/**
 * @author 董棉生(dongmiansheng@parkingwang.com)
 * @since 18-11-16
 */

class TokenConverterFactory(private val config: TokenConfig,
                            private val gson: Gson) : Converter.Factory() {

    override fun requestBodyConverter(type: Type?, parameterAnnotations: Array<Annotation>?,
                                      methodAnnotations: Array<Annotation>?, retrofit: Retrofit?): Converter<*, RequestBody>? {

        if (type is Class<*> && Params::class.java.isAssignableFrom(type) && methodAnnotations != null) {
            return if (methodAnnotations.any { NoNeedToken::class == it.annotationClass }) {
                null
            } else {
                TokenRequestConverter(config, gson)
            }
        }
        return null
    }

    companion object {
        @JvmStatic
        fun create(config: TokenConfig, gson: Gson): TokenConverterFactory {
            return TokenConverterFactory(config, gson)
        }
    }
}